<template>
  <modal :visible="visible" position="center">
    <view class="invited-member-modal">
      <image :src="imgSrc" class="top-img" mode="widthFix" />
      <view class="content">
        <view class="message">特邀专场仅限受邀会员可享，请使用受邀手机号码完成会员绑定后参与</view>
        <view class="checkbox-wrap">
          <view class="checkbox-item" @click.stop="onChangeAgeCheck" v-if="!ageModalChecked">
            <m-checkbox :value="ageCheck" :size="32" :custom-style="{ marginTop: '10rpx' }" />
            <view class="checkbox-text">内容涉及酒类知识及其他相关信息,请确认您已满18周岁</view>
          </view>
          <view class="checkbox-item" @click.stop="onChangeClauseCheck">
            <m-checkbox :value="clauseCheck" :size="32" :custom-style="{ marginTop:  '10rpx' }" />
            <view style="letter-spacing: -1rpx;" class="checkbox-text">我已阅读并同意《<text class="underline"
                @click.stop="onLinkClick">爱丁顿个人信息保护政策</text><text>》及《</text><text class="underline"
                @click.stop="handleOpenPrivacyContract">THE MACALLAN EBOUTIQUE
                麦卡伦小程序用户隐私保护指引</text>》
            </view>
          </view>
        </view>
        <view class="btn-wrap">
          <button class="common-btn subsidiary btn" @click.stop="onClose">
            关闭
          </button>
          <button v-if="checkedAll" id="agree-btn" class="common-btn btn"
            open-type="getPhoneNumber|agreePrivacyAuthorization" @getphonenumber="onGetPhoneNumber"
            @agreeprivacyauthorization="handleAgreePrivacyAuthorization">
            立即绑定
          </button>
          <button v-else class="common-btn btn" @click.stop="onCheck">
            立即绑定
          </button>
        </view>
      </view>
    </view>
  </modal>
</template>

<script>
  import modal from "../modal/modal.vue";
  import {
    invitedMemberImg,
    getMessageModalTemplate
  } from "./static.js";
  import mCheckbox from "../m-checkbox/m-checkbox.vue";
  import {
    navigateToProtectionPolicy
  } from "./utils";
  import tip from "@/utils/tip";
  import registerController from "./RegisterController";
  import RegisterTracker from "./RegisterTracker";
  import {
    mapState
  } from 'vuex';
  export default {
    name: "invited-member-modal",
    components: {
      modal,
      mCheckbox
    },
    props: {
      // 使用页面
      location: {
        type: String,
        default: "home",
      },
      tsActId: {
        type: String,
        default: "",
      },
    },
    data() {
      return {
        visible: false,
        imgSrc: invitedMemberImg,
        ageCheck: false, // 勾选年龄
        clauseCheck: false, // 勾选保护政策
        modalShowArr: [], // 三个协议的显示状态
        checkedRules: [false, false], // 协议的勾选状态
      };
    },
    computed: {
      ...mapState({
        ageModalChecked: (state) => state.ageModalChecked
      }),
      checkedAll() {
        let flag = true
        this.modalShowArr.map((item, index) => {
          if (item) {
            this.checkedRules.map((itey, indey) => {
              if (index == indey && item !== itey) {
                flag = false
              }
            })
          }
        })
        return flag
      }
    },
    methods: {
      open() {
        this.visible = true;
        this.modalShowArr = [!this.ageModalChecked, true]
      },
      close() {
        this.visible = false;
      },
      onClose() {
        this.close();
        this.$commonSensors.popupEvent('PopupClick', {
          'popup_type': 'TS活动',
          'popup_name': 'TS入会弹窗',
          'button_name': '关闭'
        })
        this.$emit("close");
      },
      onCheck() {
        // 显示几个协议
        let trueIndexArr = [];
        this.modalShowArr.map((item, index) => {
          if (item) {
            trueIndexArr.push(index)
          }
        })
        let noticeArr = []
        this.modalShowArr.map((item, index) => {
          if (item) {
            this.checkedRules.map((itey, indey) => {
              if (index == indey && item !== itey) {
                noticeArr.push(indey)
              }
            })
          }
        })
        if (trueIndexArr.length == 1) {
          if (noticeArr.length == 1) {
            this.plainTextMessge(noticeArr[0])
          }
        } else if (trueIndexArr.length == 2) {
          if (noticeArr.length == 2) {
            this.plainTextMessge(99)
          } else if (noticeArr.length >= 1) {
            this.plainTextMessge(noticeArr[0])
          }
        }
      },
      plainTextMessge(number) {
        let msg;
        if (number == 0) {
          msg = "请确认您已年满18周岁"
        } else if (number == 1) {
          msg = "请确认您阅读并同意个人信息保护政策及隐私保护指引"
        } else if (number == 99) {
          msg = "请确认您已确认全部选项"
        }
        tip.plainText(msg)
      },
      onChangeAgeCheck() {
        this.ageCheck = !this.ageCheck;
        this.$set(this.checkedRules, 0, this.ageCheck)
      },
      onChangeClauseCheck() {
        this.clauseCheck = !this.clauseCheck;
        this.$set(this.checkedRules, 1, this.clauseCheck)
      },

      onLinkClick() {
        navigateToProtectionPolicy();
      },
      // 打开隐私协议页面
      handleOpenPrivacyContract() {
        wx.openPrivacyContract({
          success: () => {}, // 打开成功
          fail: (err) => {}, // 打开失败
        })
      },
      handleAgreePrivacyAuthorization() {
        // 用户同意隐私协议事件回调
        // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了

      },
      async onGetPhoneNumber(e) {
        uni.showLoading({
          title: "正在加载",
        });
        // 显示几个协议
        let trueIndexArr = [];
        this.modalShowArr.forEach((item, index) => {
          if (item) {
            trueIndexArr.push(index)
          }
        })
        let trackParams = {}
        trueIndexArr.forEach((item) => {
          if (item == 0) {
            trackParams.c_age_answer = '允许'
          } else if (item == 1) {
            trackParams.c_pii_ppg_answer = '允许'
          }
        })
        RegisterTracker.authGate({
          trackParams,
          location: this.location,
          registerType: "TARGET_SALES",
        });
        const res = await registerController.getPhoneNumberData(e, {
          noTips: true,
          location: this.location,
          tsActId: this.tsActId,
        });
        this.$store.commit("changeAgeModalCheckedState", true);
        if (res.success) {
          this.close();
          const {
            phoneNumber
          } = res.data;
          const phoneNumberReg = /^1\d{10}$/;
          if (!phoneNumberReg.test(phoneNumber)) {
            uni.hideLoading();
            this.$emit('confirm', {
              messageModalCode: 'OVERSEAS_MEMBER'
            })
            return
          }
          const result = await registerController.getTargetSaleStatus(
            phoneNumber,
            this.tsActId
          );
          const template = getMessageModalTemplate(
            "TARGET_SALES",
            result.messageModalCode
          );
          this.$commonSensors.popupEvent('PopupClick', {
            'popup_type': 'TS活动',
            'popup_name': 'TS入会弹窗',
            'button_name': '立即绑定'
          })
          if (template?.doRegister) {
            const registerData = await registerController.register(phoneNumber);
            Object.assign(result, registerData);
          }
          uni.hideLoading();
          this.$emit("confirm", result);
          if (result.joinMemberSuccess) {
            this.$emit("registerSuccess", result);
          }
        } else {
          uni.hideLoading();
          this.close();
          this.$emit("cancel");
          this.$commonSensors.popupEvent('PopupClick', {
            'popup_type': 'TS活动',
            'popup_name': 'TS入会弹窗',
            'button_name': '立即绑定'
          })
        }
      },
    },
  };
</script>

<style lang="scss">
  @import "./common.scss";

  .invited-member-modal {
    width: 560rpx;
    background: #fff;

    .top-img {
      display: block;
      width: 100%;
    }

    .content {
      padding: 52rpx 0 56rpx 0;
    }

    .message {
      box-sizing: border-box;
      padding: 0 64rpx;
      font-size: 26rpx;
      line-height: 40rpx;
      text-align: justify;
    }

    .checkbox-wrap {
      margin-top: 30rpx;
      box-sizing: border-box;
      padding: 0 40rpx;
    }

    .checkbox-item {
      display: flex;
      margin-top: 20rpx;

      &:first-child {
        margin-top: 0;
      }

      .checkbox-text {
        margin-left: 18rpx;
        font-size: 26rpx;
        line-height: 40rpx;
      }
    }

    .btn-wrap {
      margin-top: 52rpx;
      padding: 0 50rpx;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
    }
  }
</style>
